package com.imonsoft.sqm.validator.basedata;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.imonsoft.sqm.pojo.basedata.Dictionary;
import com.imonsoft.sqm.service.MessageUtil;

@Component("dictionaryValidator")
public class DictionaryValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return Dictionary.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "message.required.dictionary.code", "code required!");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "message.required.dictionary.name", "name required!");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type", "message.required.dictionary.type", "type required!");
	}

	@Autowired
	private MessageUtil messageUtil;

	public List<String> getErrors(BindingResult result) {
		List<String> errors = new ArrayList<String>();
		for (ObjectError error : result.getAllErrors()) {
			errors.add(messageUtil.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage()));
		}
		return errors;
	}
}
